package com.nowcoder.community.entity;

import lombok.Data;

/**
 * 封装分页相关的信息.
 */
@Data
public class Page {

    private static final int MAX_LIMIT = 100;

    /**
     * 当前页码
     */
    private int current = 1;
    // 显示上限
    private int limit = 10;
    // 数据总数(用于计算总页数)
    private long rows;

    /**
     * 查询路径(用于复用分页链接), 在thymeleaf模板中渲染的path将会携带current参数.
     * 默认为当前路径下.
     */
    private String path;

    public void setCurrent(int current) {
        if (current >= 1) {
            this.current = current;
        }
    }

    public void setLimit(int limit) {
        if (limit >= 1 && limit <= MAX_LIMIT) {
            this.limit = limit;
        }
    }

    public void setRows(long rows) {
        if (rows >= 0) {
            this.rows = rows;
        }
    }

    /**
     * 获取当前页的起始行
     *
     */
    public int getOffset() {
        // current * limit - limit
        return (current - 1) * limit;
    }

    /**
     * 获取总页数
     *
     */
    public int getTotal() {
        if (rows % limit == 0) {
            return (int) (rows / limit);
        } else {
            return (int) (rows / limit + 1);
        }
    }

    /**
     * 获取起始页码
     *
     */
    public int getFrom() {
        int from = current - 2;
        return Math.max(from, 1);
    }

    /**
     * 获取结束页码
     *
     */
    public int getTo() {
        int to = current + 2;
        int total = getTotal();
        return Math.min(to, total);
    }

}
